package com.ian.service.impl;

import com.ian.domain.dto.AjaxResult;
import com.ian.domain.dto.LoginUser;
import com.ian.enums.UserStatus;
import com.ian.exception.ServiceException;
import com.ian.service.UserMgrClient;
import com.ian.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户验证处理
 *
 * @author witt
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMgrClient userMgrClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Map<String, Object> map = new HashMap<>(2);
        map.put("username", username);
        AjaxResult ajaxResult = userMgrClient.selectUserByUserName(map);
        Object data = ajaxResult.get("data");
//        LoginUser loginUser = userMgrClient.selectUserByUserName(username);
        if (StringUtils.isNull(data)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        } else {
            LoginUser loginUser = new LoginUser();
            if (data instanceof HashMap) {
                Map<String, Object> userMap = (Map) data;
                copyProperties(userMap, loginUser);
                if (UserStatus.DELETED.getCode().equals(loginUser.getDelFlag())) {
                    log.info("登录用户：{} 已被删除.", username);
                    throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
                } else if (UserStatus.DISABLED.getCode().equals(loginUser.getStatus())) {
                    log.info("登录用户：{} 已被停用.", username);
                    throw new ServiceException("对不起，您的账号：" + username + " 已停用");
                }
            }

            return loginUser;
        }
    }

    private void copyProperties(Map<String, Object> userMap, LoginUser loginUser) {
        loginUser.setUserId(Long.valueOf(String.valueOf(userMap.get("userId"))));
        loginUser.setUsername((String) userMap.get("userName"));
        loginUser.setPassword((String) userMap.get("password"));

        loginUser.setDeptId(Long.valueOf(String.valueOf(userMap.get("deptId"))));
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setStatus((String) userMap.get("status"));
        loginUser.setDelFlag((String) userMap.get("delFlag"));

        // 设置role集合
        Object roles = userMap.get("roles");
        if (StringUtils.isNotNull(roles) && roles instanceof List) {
            List<Object> roleList = (List<Object>) roles;
            List<String> roleKeys = roleList.stream().map(role -> {
                String roleKey = null;
                if (role instanceof Map) {
                    roleKey = String.valueOf(((Map<String, Object>) role).get("roleKey"));
                }
                return roleKey;
            }).collect(Collectors.toList());
            loginUser.setRoles(roleKeys);
        }

        // 设置permission集合
        Object permissions = userMap.get("permissions");
        if (StringUtils.isNotNull(permissions) && permissions instanceof List) {
            List<Object> permissionList = (List<Object>) permissions;
            List<String> permissionList2 = permissionList.stream().map(permission -> String.valueOf(permission)).collect(Collectors.toList());
            loginUser.setPermissions(permissionList2);
        }
    }
}
